package com.ContactsWitch.jackiez;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;

import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.PhoneLookup;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.ContactsWitch.jackiez.util.LogUtil; 
import com.ContactsWitch.jackiez.db.*;




public class contactswitch extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
	private DBOpenHelper mOpenHelper;
	public static final int DIALOG_UPLOAD_PROGRESS = 0;
	public static final int DIALOG_DOWNLOAD_PROGRESS = 1;

	private ProgressDialog mProgressDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btn_export = (Button)findViewById(R.id.exportbutton);
        Button btn_upload = (Button)findViewById(R.id.uploadbutton);
        Button btn_download = (Button)findViewById(R.id.downloadbutton);
        Button btn_import = (Button)findViewById(R.id.importbutton);
        
        btn_export.setOnClickListener(this);
        btn_upload.setOnClickListener(this);
        btn_download.setOnClickListener(this);
        btn_import.setOnClickListener(this);
    }
    

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.exportbutton:
			starttoexport();
			break;
		case R.id.uploadbutton:
			starttoupload();
			break;
		case R.id.downloadbutton:
			starttodownload();
			break;
		case R.id.importbutton:
			starttoimport();
			break;
			
		}
	}

	public void starttoexport(){
        Button btn_export = (Button)findViewById(R.id.exportbutton);
		mOpenHelper = new DBOpenHelper(btn_export.getContext());
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();	
        ContentResolver cr = getContentResolver();   
		Exporter exporter = new Exporter();
        exporter.ExportContacts(db,cr); 		
	}

    public void starttoupload(){
        new UploadFileAsync().execute();
    }
    
    public void starttodownload(){
    	try{
    		File dir = new File("/data/data/com.ContactsWitch.jackiez/databases/");
    		dir.mkdir();
    	}
    	catch(Exception e){
			LogUtil.LogShow("[download]", "the folder already been or creating error!", LogUtil.DEBUG);
    	}
    	String url = "http://test.bjcargo.com/ContactsWitch510.txt";
    	new DownloadFileAsync().execute(url);
    }    
    
    public void starttoimport(){
        Button btn_import = (Button)findViewById(R.id.importbutton);
		mOpenHelper = new DBOpenHelper(btn_import.getContext());
        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
        ContentResolver cr = getContentResolver();   
        Importer importer = new Importer();
        importer.ImportContacts(db,cr);
    }
    
    
    @Override
    protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_UPLOAD_PROGRESS:
    mProgressDialog = new ProgressDialog(this);
    mProgressDialog.setMessage("Uploading file..");
    //mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mProgressDialog.setCancelable(false);
    mProgressDialog.show();
    return mProgressDialog;
    case DIALOG_DOWNLOAD_PROGRESS:
    mProgressDialog = new ProgressDialog(this);
    mProgressDialog.setMessage("Downloading file..");
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mProgressDialog.setCancelable(false);
    mProgressDialog.show();
    return mProgressDialog;
    default:
    return null;
    }
    }
    
	//The Uploading AsyncTask
	class UploadFileAsync extends AsyncTask< String, String, String> {
		
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		showDialog(DIALOG_UPLOAD_PROGRESS);
	}
	
	/*
	@Override
	protected String doInBackground(String... aurl) {
		LogUtil.LogShow("[upload]", "Begin to Upload", LogUtil.DEBUG);
		int count = 0;
    	FTPClient ftp = new FTPClient();
    	String server = "203.171.225.126";
    	String username="zhaojian";
    	String password="Huaren178";
    	String file="/data/data/com.ContactsWitch.jackiez/databases/ContactsWitch.db";
		try{
    		ftp.setDefaultTimeout(30000);
    		ftp.connect(server);
    		ftp.login(username,password);
    		ftp.setDefaultPort(21);
    		int reply = ftp.getReplyCode();
			LogUtil.LogShow("[upload]", Integer.toString(reply), LogUtil.DEBUG);

    		if(!FTPReply.isPositiveCompletion(reply)){
    			ftp.disconnect();
    			//showDialog("FTP Server connecting failed!!!");
    		}
    		else{
    			LogUtil.LogShow("[upload]", Integer.toString(reply), LogUtil.DEBUG);
				ftp.enterLocalPassiveMode();
				//ftp.setControlEncoding("gbk");
				ftp.setFileType(FTP.BINARY_FILE_TYPE);
				FileInputStream fis = new FileInputStream(new File(file));
				long total = 0;
				byte data[] = new byte[1024];
				File f=new File(file); 
				//Long len=f.length(); 
				long lenghtOfFile = f.length();
    			LogUtil.LogShow("[upload]", Long.toString(lenghtOfFile), LogUtil.DEBUG);
				while ((count = fis.read(data)) != -1) {
					total += count;
					publishProgress(""+(int)((total*100)/lenghtOfFile));
					//output.write(data, 0, count);
					ftp.storeFile("ContactsWitch510.txt", fis);   				
				}
				//ftp.storeFile("ContactsWitch510.txt", fis);   				
				ftp.logout();
				LogUtil.LogShow("[upload]", "12345", LogUtil.DEBUG);
    		}
    	}
		catch(Exception e){
			LogUtil.LogShow("[upload]", "Something Wrong!", LogUtil.DEBUG);
		}
    	finally
    	{
    		if(ftp.isConnected()){
    			try{
    				ftp.disconnect();
    			}
    			catch(Exception ioe){
    				LogUtil.LogShow("[upload]", "Something Wrong!", LogUtil.DEBUG);
    			}
    		}
    	}		
		return null;

	}
	/*
	 *
	 */
	@Override
	protected String doInBackground(String... aurl) {
		Uploader uploader = new Uploader();
		uploader.UploadContacts();
		return null;
	}

	@Override
	protected void onProgressUpdate(String... progress) {
		Log.d("ANDRO_ASYNC",progress[0]);
		mProgressDialog.setProgress(Integer.parseInt(progress[0]));
		}

		 
	@Override
	protected void onPostExecute(String unused) {
		dismissDialog(DIALOG_UPLOAD_PROGRESS);
		}
	}
	
	
	//The downloading Asynctask
	class DownloadFileAsync extends AsyncTask< String, String, String> {
		
		@Override
		protected void onPreExecute() {
		super.onPreExecute();
		showDialog(DIALOG_DOWNLOAD_PROGRESS);
		}
	/*
		@Override
		protected String doInBackground(String... aurl) {
			try {
				URL url = new URL(aurl[0]);
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Downloader downloader = new Downloader();
			
			return null;
		}	
	*/	
	 
		@Override
		protected String doInBackground(String... aurl) {
		int count;
		try {
		URL url = new URL(aurl[0]);
		URLConnection conexion = url.openConnection();
		conexion.connect();
		int lenghtOfFile = conexion.getContentLength();
		Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
		InputStream input = new BufferedInputStream(url.openStream());
		OutputStream output = new FileOutputStream("/data/data/com.ContactsWitch.jackiez/databases/ContactsWitch.db");
		byte data[] = new byte[1024];
		long total = 0;
		while ((count = input.read(data)) != -1) {
		total += count;
		publishProgress(""+(int)((total*100)/lenghtOfFile));
		output.write(data, 0, count);
		}
		output.flush();
		output.close();
		input.close();
		} catch (Exception e) {
		Log.e("error",e.getMessage().toString());
		System.out.println(e.getMessage().toString());
		}
		return null;
		}
		
	
		protected void onProgressUpdate(String... progress) {
		Log.d("ANDRO_ASYNC",progress[0]);
		mProgressDialog.setProgress(Integer.parseInt(progress[0]));
		}

		 
		@Override
		protected void onPostExecute(String unused) {
		dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
		}
		}
	
	
	
	}
